package com.atguigu.study.rwlock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//class Cache{
//    Map<String,String> map=new HashMap<>();
//    public synchronized  void write(String key,String value){
//        System.out.println(Thread.currentThread().getName()+"正在写入");
//        map.put(key, value);
//        System.out.println(Thread.currentThread().getName()+"完成写入");
//    }
//    public synchronized  void read(String key){
//        System.out.println(Thread.currentThread().getName()+"正在读取");
//        map.get(key);
//        System.out.println(Thread.currentThread().getName()+"完成读取");
//    }
//}


//class Cache{
//    Map<String,String> map=new HashMap<>();
//    private final Lock lock=new ReentrantLock();
//    public   void write(String key,String value){
//        lock.lock();
//        try {
//            System.out.println(Thread.currentThread().getName()+"正在写入");
//            map.put(key, value);
//            System.out.println(Thread.currentThread().getName()+"完成写入");
//        } finally {
//            lock.unlock();
//        }
//    }
//    public  void read(String key){
//        lock.lock();
//        try {
//            System.out.println(Thread.currentThread().getName()+"正在读取");
//            map.get(key);
//            System.out.println(Thread.currentThread().getName()+"完成读取");
//        } finally {
//            lock.unlock();
//        }
//    }
//}

class Cache{
    Map<String,String> map=new HashMap<>();
    private final ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    public   void write(String key,String value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"完成写入");
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public  void read(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读取----->"+result);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        Cache cache = new Cache();

        for (int i = 1; i <= 5; i++) {
            int finaI=i;
            new Thread(()->{
                cache.write(finaI+"",finaI+"");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            int finaI=i;
            new Thread(()->{
                cache.read(finaI+"");
            },String.valueOf(i)).start();
        }
    }
}
